package cn.pubinfo.service.impl;

import cn.pubinfo.controller.AdminOnly;
import cn.pubinfo.dao.UserMapper;
import cn.pubinfo.model.User;
import cn.pubinfo.model.UserExample;
import cn.pubinfo.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by zck on 2017/8/4.
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    @AdminOnly
    public User getById(int id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public User getByUsername(String username) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<User> userList = userMapper.selectByExample(example);
        if (userList.size() == 1) {
            return userList.get(0);
        }
        return null;
    }

    @Override
    public int add(User user) {
        return userMapper.insertSelective(user);
    }

    @Override
    public int delById(int id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int updateLastLoginIp(User user) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(user.getUsername());
        User tempUser = new User();
        tempUser.setLastLoginIp(user.getLastLoginIp());
        return userMapper.updateByExampleSelective(tempUser, example);
    }
}
